package controller;

import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import app.fitness.fragment.DashBoardFragment;

import com.razerzone.android.fitness.R;

public class DownloadImageAsync extends AsyncTask<String, Void, Boolean> {
	/**
	 * Data section
	 */
	private static Bitmap mBitmap;

	/**
	 * View section
	 */
	private ImageView mIvAvatar;

	public DownloadImageAsync(ImageView bmImage) {
		this.mIvAvatar = bmImage;
	}

	@Override
	protected Boolean doInBackground(String... urls) {
		String URL = urls[0];
		Bitmap mBitmap = null;

		try {
			InputStream mIs = new java.net.URL(URL).openStream();
			mBitmap = BitmapFactory.decodeStream(mIs);

			DownloadImageAsync.mBitmap = mBitmap;
			return true;
		} catch (Exception e) {
		}

		return false;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		// Set bitmap to set on the others page
		if (result) {
			mIvAvatar.setImageBitmap(mBitmap);

			/**
			 * Save avatar into single ton
			 */
			DashBoardFragment.singleTon.setBitmapAvatar(mBitmap);
		} else {
			mIvAvatar.setImageResource(R.drawable.ic_default_avatar);
		}
	}

	/**
	 * Basic methods
	 */

	public static Bitmap getBitmap() {
		return mBitmap;
	}
}
